// LiveValidation 1.3 (standalone version)
// Copyright (c) 2007-2008 Alec Hill (www.livevalidation.com)
// LiveValidation is licensed under the terms of the MIT License
/*********************************************** LiveValidation class ***********************************/

/**
 *	validates a form field in real-time based on validations you assign to it
 *	
 *	@var element {mixed} - either a dom element reference or the string id of the element to validate
 *	@var optionsObj {Object} - general options, see below for details
 *
 *	optionsObj properties:
 *							validMessage {String} 	- 通过验证后的提示信息
 *													  (DEFAULT: "正确！")
 *							onValid {Function} 		- 通过验证后执行的事件
 *													  (DEFAULT: function(){ this.insertMessage(this.createMessageSpan()); this.addFieldClass(); } )	
 *							onInvalid {Function} 	- 没通过验证执行的事件
 *													  (DEFAULT: function(){ this.insertMessage(this.createMessageSpan()); this.addFieldClass(); })
 *							insertAfterWhatNode {Int} 	- position to insert default message
 *													  (DEFAULT: the field that is being validated)	
 *              onlyOnBlur {Boolean} - whether you want it to validate as you type or only on blur
 *                            (DEFAULT: false)
 *              wait {Integer} - 最后点击这前的时间后才开始验证
 *                            (DEFAULT: 0)
 *              onlyOnSubmit {Boolean} - 是否进行验证时才提交
 *                            (DEFAULT: false)						
 */
var lv_submitno = true;
var LiveValidation = function(element, optionsObj) {
    this.initialize(element, optionsObj)
};
LiveValidation.VERSION = '1.3 standalone';
LiveValidation.TEXTAREA = 1;
LiveValidation.TEXT = 2;
LiveValidation.PASSWORD = 3;
LiveValidation.CHECKBOX = 4;
LiveValidation.SELECT = 5;
LiveValidation.FILE = 6;
LiveValidation.RADIO = 7;
LiveValidation.massValidate = function(validations) {
    var returnValue = true;
    for (var i = 0,
    len = validations.length; i < len; ++i) {
        var valid = validations[i].validate(1);
        if (returnValue) returnValue = valid
    };
    lv_submitno = returnValue;
    return returnValue
};
LiveValidation.prototype = {
    validClass: 'LV_valid',
    invalidClass: 'LV_invalid',
    selectedClass: 'LV_selected',
    messageClass: 'LV_validation_message',
    validFieldClass: 'LV_valid_field',
    invalidFieldClass: 'LV_invalid_field',
    selectedFieldClass: 'LV_selected_field',
    initialize: function(element, optionsObj) {
        var self = this;
        if (!element) throw new Error("LiveValidation::initialize - No element reference or element id has been provided!");
        this.element = element.nodeName ? element: document.getElementById(element);
        if (!this.element) throw new Error("LiveValidation::initialize - No element with reference or id of '" + element + "' exists!");
        this.validations = [];
        this.elementType = this.getElementType();
        this.form = this.element.form;
        var options = optionsObj || {};
        this.validMessage = options.validMessage || '已输入！';
        this.selectedMessage = options.selectedMessage || '请输入';
        var node = options.insertAfterWhatNode || this.element;
        this.insertAfterWhatNode = node.nodeType ? node: document.getElementById(node);
		this.onsubmitValidno=options.onsubmitValidno||true;
        this.onValid = options.onValid ||
        function() {
            this.selected = false;
            this.insertMessage(this.createMessageSpan());
            this.addFieldClass()
        };
        this.onInvalid = options.onInvalid ||
        function() {
            this.selected = false;
            this.insertMessage(this.createMessageSpan());
            this.addFieldClass()
        };
        this.onSelected = options.onSelected ||
        function() {
            this.message = this.selectedMessage;
            this.displayMessageWhenEmpty = true;
            this.selected = true;
            this.insertMessage(this.createMessageSpan());
            this.addSelectedClass()
        };
        this.onlyOnBlur = options.onlyOnBlur || true;

        this.wait = options.wait || 0;
        this.onlyOnSubmit = options.onlyOnSubmit || false;
        if (this.form) {
            this.formObj = LiveValidationForm.getInstance(this.form);
            this.formObj.addField(this)
        };
        this.oldOnFocus = this.element.onfocus ||
        function() {};
        this.oldOnBlur = this.element.onblur ||
        function() {};
        this.oldOnClick = this.element.onclick ||
        function() {};
        this.oldOnChange = this.element.onchange ||
        function() {};
        this.oldOnKeyup = this.element.onkeyup ||
        function() {};
        this.element.onfocus = function(e) {
            self.doOnFocus(e);
            return self.oldOnFocus.call(this, e)
        };
        if (!this.onlyOnSubmit) {
            switch (this.elementType) {
            case LiveValidation.CHECKBOX:
            case LiveValidation.RADIO:
                {
                    this.element.onclick = function(e) {
                        self.validate();
                        return self.oldOnClick.call(this, e)
                    }
                }
            case LiveValidation.SELECT:
            case LiveValidation.FILE:
                {
                    this.element.onchange = function(e) {
                        self.validate();
                        return self.oldOnChange.call(this, e)
                    };
                    this.element.onblur = function(e) {
                        self.doOnBlur(e);
                        return self.oldOnBlur.call(this, e)
                    };
                    break
                }
            default:
                {
                    if (!this.onlyOnBlur) this.element.onkeyup = function(e) {
                        self.deferValidation();
                        return self.oldOnKeyup.call(this, e)
                    };
                    this.element.onblur = function(e) {
                        self.doOnBlur(e);
                        return self.oldOnBlur.call(this, e)
                    }
                }
            }
        }
    },
    destroy: function() {
        if (this.formObj) {
            this.formObj.removeField(this);
            this.formObj.destroy()
        };
        this.element.onfocus = this.oldOnFocus;
        if (!this.onlyOnSubmit) {
            switch (this.elementType) {
            case LiveValidation.CHECKBOX:
            case LiveValidation.RADIO:
                this.element.onclick = this.oldOnClick;
            case LiveValidation.SELECT:
            case LiveValidation.FILE:
                this.element.onchange = this.oldOnChange;
                break;
            default:
                if (!this.onlyOnBlur) this.element.onkeyup = this.oldOnKeyup;
                this.element.onblur = this.oldOnBlur
            }
        }
        this.validations = [];
        this.removeMessageAndFieldClass()
    },
    add: function(validationFunction, validationParamsObj) {
        this.validations.push({
            type: validationFunction,
            params: validationParamsObj || {}
        });
        return this
    },
    remove: function(validationFunction, validationParamsObj) {
        var found = false;
        for (var i = 0,
        len = this.validations.length; i < len; i++) {
            if (this.validations[i].type == validationFunction) {
                if (this.validations[i].params == validationParamsObj) {
                    found = true;
                    break
                }
            }
        }
        if (found) this.validations.splice(i, 1);
        return this
    },
    deferValidation: function(e) {
        if (this.wait >= 300) this.removeMessageAndFieldClass();
        var self = this;
        if (this.timeout) clearTimeout(self.timeout);
        this.timeout = setTimeout(function() {
            self.validate()
        },
        self.wait)
    },
    doOnBlur: function(e) {
        this.focused = false;
        this.validate(e)
    },
    doOnFocus: function(e) {
        this.focused = true;
        this.removeMessageAndFieldClass();
        this.onSelected()
    },
    getElementType: function() {
        switch (true) {
        case(this.element.nodeName.toUpperCase() == 'TEXTAREA') : return LiveValidation.TEXTAREA;
        case(this.element.nodeName.toUpperCase() == 'INPUT' && this.element.type.toUpperCase() == 'TEXT') : return LiveValidation.TEXT;
        case(this.element.nodeName.toUpperCase() == 'INPUT' && this.element.type.toUpperCase() == 'PASSWORD') : return LiveValidation.PASSWORD;
        case(this.element.nodeName.toUpperCase() == 'INPUT' && this.element.type.toUpperCase() == 'CHECKBOX') : return LiveValidation.CHECKBOX;
        case(this.element.nodeName.toUpperCase() == 'INPUT' && this.element.type.toUpperCase() == 'RADIO') : return LiveValidation.RADIO;
        case(this.element.nodeName.toUpperCase() == 'INPUT' && this.element.type.toUpperCase() == 'FILE') : return LiveValidation.FILE;
        case(this.element.nodeName.toUpperCase() == 'SELECT') : return LiveValidation.SELECT;
        case(this.element.nodeName.toUpperCase() == 'INPUT') : throw new Error('LiveValidation::getElementType - Cannot use LiveValidation on an ' + this.element.type + ' input!');
        default:
            throw new Error('LiveValidation::getElementType - Element must be an input, select, or textarea!')
        }
    },
    doValidations: function() {
        this.validationFailed = false;
        for (var i = 0,
        len = this.validations.length; i < len; ++i) {
            var validation = this.validations[i];
            switch (validation.type) {
            case Validate.Presence:
            case Validate.Confirmation:
            case Validate.Acceptance:
                this.displayMessageWhenEmpty = true;
                this.validationFailed = !this.validateElement(validation.type, validation.params);
                break;
            default:
                this.validationFailed = !this.validateElement(validation.type, validation.params);
                break
            }
            if (this.validationFailed) return false
        }
        this.message = this.validMessage;
        return true
    },
    validateElement: function(validationFunction, validationParamsObj) {
        var value = (this.elementType == LiveValidation.SELECT) ? this.element.options[this.element.selectedIndex].value: this.element.value;
        if (validationFunction == Validate.Acceptance) {
            var r_name = $(this.element).attr("name");
            switch (this.elementType) {
            case LiveValidation.CHECKBOX:
                {
                    var cbox_list = $("input:checkbox[name='" + r_name + "']:checked");
                    break
                }
            case LiveValidation.RADIO:
                {
                    var cbox_list = $("input:radio[name='" + r_name + "']:checked");
                    break
                }
            default:
                {
                    throw new Error('LiveValidation::validateElement - Element to validate acceptance must be a checkbox!')
                }
            }
            if (cbox_list.size() > 0) {
                value = true
            } else {
                value = false
            }
        }
        var isValid = true;
        try {
            validationFunction(value, validationParamsObj)
        } catch(error) {
            if (error instanceof Validate.Error) {
                if (value !== '' || (value === '' && this.displayMessageWhenEmpty)) {
                    this.validationFailed = true;
                    this.message = error.message;
                    isValid = false
                }
            } else {
                throw error
            }
        } finally {
            return isValid
        }
    },
    validate: function(typ) {
        if (!this.element.disabled) {
            var isValid = this.doValidations();
            if (isValid) {
                if(typ!=1){this.onValid();}
                return true
            } else {
                this.onInvalid();
                return false
            }
        } else {
            return true
        }
    },
    enable: function() {
        $(this.element).attr("disabled", false);
        return this
    },
    disable: function() {
        this.element.disabled = true;
        this.removeMessageAndFieldClass();
        return this
    },
    createMessageSpan: function() {
        var span = $("<span></span>").append("<font>" + this.message + "</font>");
        return span[0]
    },
    insertMessage: function(elementToInsert) {
        this.removeMessage();
        if ((this.displayMessageWhenEmpty && (this.elementType == LiveValidation.CHECKBOX || $(this.element).val() == '')) || $(this.element).val() != '') {
            $(elementToInsert).addClass(this.messageClass);
            $(elementToInsert).addClass(this.selected ? this.selectedClass: (this.validationFailed ? this.invalidClass: this.validClass));
            if ($(this.insertAfterWhatNode).next()) {
                $(this.insertAfterWhatNode).after(elementToInsert)
            } else {
                $(this.insertAfterWhatNode).parent().append(elementToInsert)
            }
        }
    },
    addFieldClass: function() {
        this.removeFieldClass();
        if (!this.validationFailed) {
            if (this.displayMessageWhenEmpty || this.element.value != '') {
                if (!$(this.element).hasClass(this.validFieldClass)) $(this.element).addClass(this.validFieldClass)
            }
        } else {
            if (!$(this.element).hasClass(this.invalidFieldClass)) $(this.element).addClass(this.invalidFieldClass)
        }
    },
    addSelectedClass: function() {
        this.removeFieldClass();
        if (!$(this.element).hasClass(this.selectedFieldClass)) $(this.element).addClass(this.selectedFieldClass)
    },
    removeMessage: function() {
        $(this.insertAfterWhatNode).nextAll("." + this.messageClass).remove()
    },
    removeFieldClass: function() {
        $(this.element).removeClass(this.invalidFieldClass);
        $(this.element).removeClass(this.validFieldClass);
        $(this.element).removeClass(this.selectedFieldClass)
    },
    removeMessageAndFieldClass: function() {
        this.removeMessage();
        this.removeFieldClass()
    }
};
var LiveValidationForm = function(element) {
    this.initialize(element)
};
LiveValidationForm.instances = {};
LiveValidationForm.getInstance = function(element) {
    var rand = Math.random() * Math.random();
    if (!element.id) element.id = 'formId_' + rand.toString().replace(/\./, '') + new Date().valueOf();
    if (!LiveValidationForm.instances[element.id]) LiveValidationForm.instances[element.id] = new LiveValidationForm(element);
    return LiveValidationForm.instances[element.id]
};
LiveValidationForm.prototype = {
    initialize: function(element) {
        this.name = element.id;
        this.element = element;
        this.fields = [];
        this.oldOnSubmit = this.element.onsubmit ||
        function() {};
        var self = this;
        this.element.onsubmit = function(e) {
            return (LiveValidation.massValidate(self.fields)) ? self.oldOnSubmit.call(this, e || window.event) !== false: false
        }
    },
    addField: function(newField) {
        this.fields.push(newField)
    },
    removeField: function(victim) {
        var victimless = [];
        for (var i = 0,
        len = this.fields.length; i < len; i++) {
            if (this.fields[i] !== victim) victimless.push(this.fields[i])
        }
        this.fields = victimless
    },
    destroy: function(force) {
        if (this.fields.length != 0 && !force) return false;
        this.element.onsubmit = this.oldOnSubmit;
        LiveValidationForm.instances[this.name] = null;
        return true
    }
};
var Validate = {
    Presence: function(value, paramsObj) {
        var paramsObj = paramsObj || {};
        var message = paramsObj.failureMessage || "不能为空！";
        if (value === '' || value === null || value === undefined) {
            Validate.fail(message)
        }
        return true
    },
    Numericality: function(value, paramsObj) {
        var suppliedValue = value;
        var value = Number(value);
        var paramsObj = paramsObj || {};
        var minimum = ((paramsObj.minimum) || (paramsObj.minimum == 0)) ? paramsObj.minimum: null;
        var maximum = ((paramsObj.maximum) || (paramsObj.maximum == 0)) ? paramsObj.maximum: null;
        var is = ((paramsObj.is) || (paramsObj.is == 0)) ? paramsObj.is: null;
        var notANumberMessage = paramsObj.notANumberMessage || "必需是数字！";
        var notAnIntegerMessage = paramsObj.notAnIntegerMessage || "必需是整数！";
        var wrongNumberMessage = paramsObj.wrongNumberMessage || "必需是 " + is + "！";
        var tooLowMessage = paramsObj.tooLowMessage || "必需大于 " + minimum + "!";
        var tooHighMessage = paramsObj.tooHighMessage || "必需小于 " + maximum + "!";
        if (!isFinite(value)) Validate.fail(notANumberMessage);
        if (paramsObj.onlyInteger && (/\.0+$|\.$/.test(String(suppliedValue)) || value != parseInt(value))) Validate.fail(notAnIntegerMessage);
        switch (true) {
        case(is !== null) : if (value != Number(is)) Validate.fail(wrongNumberMessage);
            break;
        case (minimum !== null && maximum !== null) : Validate.Numericality(value, {
                tooLowMessage: tooLowMessage,
                minimum: minimum
            });
            Validate.Numericality(value, {
                tooHighMessage: tooHighMessage,
                maximum: maximum
            });
            break;
        case (minimum !== null) : if (value < Number(minimum)) Validate.fail(tooLowMessage);
            break;
        case (maximum !== null) : if (value > Number(maximum)) Validate.fail(tooHighMessage);
            break
        }
        return true
    },
    Format: function(value, paramsObj) {
        var value = String(value);
        var paramsObj = paramsObj || {};
        var message = paramsObj.failureMessage || "不是一个有效的内容！";
        var pattern = paramsObj.pattern || /./;
        var negate = paramsObj.negate || false;
        var allowNull = paramsObj.allowNull || false;
        if (allowNull && (value == "" || value == null)) {
            return true
        }
        if (!negate && !pattern.test(value)) Validate.fail(message);
        if (negate && pattern.test(value)) Validate.fail(message);
        return true
    },
    Email: function(value, paramsObj) {
        var paramsObj = paramsObj || {};
        var message = paramsObj.failureMessage || "必需是一个有效的电子邮件地址！";
        var allowNull = paramsObj.allowNull || false;
        Validate.Format(value, {
            failureMessage: message,
			allowNull:allowNull,
            pattern: /^([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})$/i
        });
        return true
    },
    Length: function(value, paramsObj) {
        var value = String(value);
        var paramsObj = paramsObj || {};
        var minimum = ((paramsObj.minimum) || (paramsObj.minimum == 0)) ? paramsObj.minimum: null;
        var maximum = ((paramsObj.maximum) || (paramsObj.maximum == 0)) ? paramsObj.maximum: null;
        var is = ((paramsObj.is) || (paramsObj.is == 0)) ? paramsObj.is: null;
        var wrongLengthMessage = paramsObj.wrongLengthMessage || "必需 " + is + " 个字符！";
        var tooShortMessage = paramsObj.tooShortMessage || "不能低于 " + minimum + " 个字符！";
        var tooLongMessage = paramsObj.tooLongMessage || "不能高于 " + maximum + " 个字符！";
        switch (true) {
        case(is !== null) : if (value.length2 != Number(is)) Validate.fail(wrongLengthMessage);
            break;
        case (minimum !== null && maximum !== null) : Validate.Length(value, {
                tooShortMessage: tooShortMessage,
                minimum: minimum
            });
            Validate.Length(value, {
                tooLongMessage: tooLongMessage,
                maximum: maximum
            });
            break;
        case (minimum !== null) : if (value.length2 < Number(minimum)) Validate.fail(tooShortMessage);
            break;
        case (maximum !== null) : if (value.length2 > Number(maximum)) Validate.fail(tooLongMessage);
            break;
        default:
            throw new Error("Validate::Length - Length(s) to validate against must be provided!")
        }
        return true
    },
    Inclusion: function(value, paramsObj) {
        var paramsObj = paramsObj || {};
        var message = paramsObj.failureMessage || "必需是列出的值之一！";
        var caseSensitive = (paramsObj.caseSensitive === false) ? false: true;
        if (paramsObj.allowNull && (value == null || value == "")) return true;
        if (!paramsObj.allowNull && (value == null || value == "")) Validate.fail(message);
        var within = paramsObj.within || [];
        if (!caseSensitive) {
            var lowerWithin = [];
            for (var j = 0,
            length = within.length; j < length; ++j) {
                var item = within[j];
                if (typeof item == 'string') item = item.toLowerCase();
                lowerWithin.push(item)
            }
            within = lowerWithin;
            if (typeof value == 'string') value = value.toLowerCase()
        }
        var found = false;
        for (var i = 0,
        length = within.length; i < length; ++i) {
            if (within[i] == value) found = true;
            if (paramsObj.partialMatch) {
                if (value.indexOf(within[i]) != -1) found = true
            }
        }
        if ((!paramsObj.negate && !found) || (paramsObj.negate && found)) Validate.fail(message);
        return true
    },
    Exclusion: function(value, paramsObj) {
        var paramsObj = paramsObj || {};
        paramsObj.failureMessage = paramsObj.failureMessage || "内容不能属于列出的值之一！";
        paramsObj.negate = true;
        Validate.Inclusion(value, paramsObj);
        return true
    },
    Confirmation: function(value, paramsObj) {
        if (!paramsObj.match) throw new Error("验证::确认 - 错误验证确认: 必需提供元素匹配ID!");
        var paramsObj = paramsObj || {};
        var message = paramsObj.failureMessage || "Does not match!";
        var match = paramsObj.match.nodeName ? paramsObj.match: document.getElementById(paramsObj.match);
        if (!match) throw new Error("验证::确认 - 有没有名称, 或与对象的元素的引用 '" + paramsObj.match + "'!");
        if (value != match.value) {
            Validate.fail(message)
        }
        return true
    },
    Acceptance: function(value, paramsObj) {
        var paramsObj = paramsObj || {};
        var message = paramsObj.failureMessage || "必需选中至少一个项！";
        if (!value) {
            Validate.fail(message)
        }
        return true
    },
    Custom: function(value, paramsObj) {
        var paramsObj = paramsObj || {};
        var against = paramsObj.against ||
        function() {
            return true
        };
        var args = paramsObj.args || {};
        var message = paramsObj.failureMessage || "不是一个有效的内容！";
        if (!against(value, args)) Validate.fail(message);
        return true
    },
    now: function(validationFunction, value, validationParamsObj) {
        if (!validationFunction) throw new Error("Validate::now - Validation function must be provided!");
        var isValid = true;
        try {
            validationFunction(value, validationParamsObj || {})
        } catch(error) {
            if (error instanceof Validate.Error) {
                isValid = false
            } else {
                throw error
            }
        } finally {
            return isValid
        }
    },
    fail: function(errorMessage) {
        throw new Validate.Error(errorMessage)
    },
    Error: function(errorMessage) {
        this.message = errorMessage;
        this.name = 'ValidationError'
    }
}